# 多线程通信queue.Queue
# 1. 导入类库  import queue
# 2. 创建Queue  q=queue.Queue()
# 3. 添加元素  q.put(item)
# 4. 获取元素  item = q.get()
# 5. 查询状态
    # 查看元素多少  q.qsize()
    # 判断是否为空  q.empty()
    # 判断是否已满  q.full()

import requests
import threading
from bs4 import BeautifulSoup

urls = [f"https://www.baidu.com/#p{page}" for page in range(1, 50+1)]

def craw(url):
    r = requests.get(url)
    return r.text

def parse(html):
    soup = BeautifulSoup(html, 'html.parser')
    links = soup.find_all("a", class_="post-item-title")  # html 中 a 标签，class_后面是 a 标签内容
    return [(link["href"], link.get_text()) for link in links]

# parse(craw(urls[0]))

# ---------------------------------------------------------------------
import queue
import time
import random

def do_craw(url_queue:queue.Queue, html_queue:queue.Queue):
    while True:
        url = url_queue.get()
        html = craw(url)
        html_queue.put(html)
        time.sleep(random.randint(1, 2))

def do_parse(html_queue:queue.Queue, fout):
    while True:
        html = html_queue.get()
        results = parse(html)
        for result in results:
            fout.write(str(result) + '\n')
        time.sleep(random.randint(1, 2))



if __name__ == '__main__':
    url_queue = queue.Queue()
    html_queue = queue.Queue()

    for url in urls:
        url_queue.put(url)

    for idx in range(3):  # 3个生产者线程
        t = threading.Thread(target=do_craw, args=(url_queue, html_queue), name=f"craw{idx}")
        t.start()

    fout = open("2-data.txt", "w")   # 文件输出对象
    for idx in range(2):  # 3个消费者线程
        t = threading.Thread(target=do_parse, args=(html_queue, fout), name=f"parse{idx}")
        t.start()


